package com.scse.bms.web.admin;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scse.bms.config.AppConfig;
import com.scse.bms.domain.UserHeadImgVO;
import com.scse.bms.entity.HeadImgDO;
import com.scse.bms.service.HeadImgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * @Title: HeadImgController
 * @Author: 吴赠禹
 * @Date: 2021/3/1 22:11
 * @Version: 1.0
 * @Description: TODO
 */

@Slf4j
@Controller
public class HeadImgController {

    @Resource
    private AppConfig appConfig;

    @Autowired
    private HeadImgService headImgService;


    @GetMapping("/admin/headImgList")
    public String getHeadImgList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                 @RequestParam(required = false, defaultValue = "12") Integer limit,
                                 Model model) {
        log.info("[getHeadImgList]  获取所有头像");
        log.info("==================");
        Page<UserHeadImgVO> page = new Page<>(pageNum, limit);
        IPage<UserHeadImgVO> list = headImgService.getHeadImgVOList(page);
        log.info(page.toString());
        log.info(list.toString());
        model.addAttribute("list", list);
        return "back/headImgList";
    }

    @PostMapping("/headImg/upload")
    @ResponseBody
    public String uploadHeadImg(MultipartFile file) {
        log.info("[uploadHeadImg] 上传用户头像");
        String fileName = file.getOriginalFilename();
        // 指定存储目录
        String dirPath = appConfig.getHeadImgDir();
        createIfNoExists(dirPath);
        try {
            file.transferTo(new File(dirPath + fileName));
            // 插入数据库
            int result = headImgService.addHeadImg(new HeadImgDO(dirPath + fileName, DateUtil.now()));
            log.info("[uploadHeadImg] 上传用户头像成功！");
            return String.valueOf(result);
        } catch (Exception e) {
            log.info("[uploadHeadImg] 上传用户头像失败！" + e.getMessage());
            return String.valueOf(0);
        }
    }


    /**
     * 创建文件目录
     * @param dir
     */
    private void createIfNoExists(String dir) {
        File filePath = new File(dir);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
    }

}
